package com.yyfax.infrastructure.network;

import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import com.yyfax.common.CLog;
import com.yyfax.infrastructure.Constants;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.Response;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

/**
 * Created by HenryZhang on 2017/6/20.<br>
 * Copyright © 2017 www.yylending.com. All Rights Reserved.<br><br>
 *
 * 目前为止只有同步服务器时间的逻辑，以后根据需求会加其他特性
 */
public class ResponseInterceptor implements Interceptor {
	private static final String TAG = "ResponseInterceptor";

	private boolean mFirstRequest = true;

	@Override
	public Response intercept(@NonNull Chain chain) throws IOException {
		Response response = chain.proceed(chain.request());
		if (mFirstRequest) {
			Headers headers = response.headers();
			String serverDateStr = headers.get("Date");//Thu, 29 Sep 2016 07:57:42 GMT
			CLog.i(TAG, "serverDateStr = " + serverDateStr);
			if (!TextUtils.isEmpty(serverDateStr)) {
				final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z", Locale.ENGLISH);
				TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));
				try {
					Date serverDate = simpleDateFormat.parse(serverDateStr);
					Constants.TIME_DELTA = serverDate.getTime();

					Constants.TIME_ELAPSED = SystemClock.elapsedRealtime();//开机时间
					CLog.i(TAG, "serverDate = " + serverDate.toString() +
							", delta = " + Constants.TIME_DELTA + ", elapsed = " + Constants.TIME_ELAPSED);

					mFirstRequest = false;
				} catch (Exception e) {
					mFirstRequest = true;
					CLog.e(TAG, "Getting Server Data Exception: " + e.getMessage());
				}
			} else {
				//see [Android通过NTP服务器自动获取时间的方法](http://blog.csdn.net/mapdigit/article/details/7669325)
				CLog.e(TAG, "Empty Value of Data in Response");
			}
		}
		return response;
	}
}
